using Microsoft.SqlServer.Management.Sdk.Sfc;
using System;
using System.Collections.Generic;

namespace Microsoft.SqlServer.Management.SqlManagerUI.Scripting
{
	internal class DependencyScriptHandler : ScriptHandler
	{
		private ScriptedObjectCollection objectsScripted = new ScriptedObjectCollection();

		private ScriptActions scriptType;

		public DependencyScriptHandler(IEnumerable<Urn> objectOrder, ScriptActions scriptType) : this(objectOrder, scriptType, null)
		{
		}

		public DependencyScriptHandler(IEnumerable<Urn> objectOrder, ScriptActions scriptType, ScriptHandler successor) : base(successor)
		{
			this.scriptType = scriptType;
			this.PopulateScriptedList(objectOrder);
		}

		protected override bool HandleScriptedEventCore(ObjectScriptedEventArgs e)
		{
			if (this.scriptType == ScriptActions.None || (this.scriptType & e.Action) == ScriptActions.None)
			{
				return false;
			}
			if (e.ObjectInfo.Urn.Type == "UserDefinedDataType" && (e.Action & ScriptActions.Bindings) != ScriptActions.None)
			{
				return false;
			}
			if (!this.objectsScripted.Contains(e.ObjectInfo.Urn))
			{
				return false;
			}
			this.objectsScripted.AddScriptFragment(e.ObjectInfo, e.Script, e.Action);
			return true;
		}

		protected override void ScriptCore(ScriptWriter scriptWriter)
		{
			this.objectsScripted.ScriptAll(scriptWriter);
		}

		private void PopulateScriptedList(IEnumerable<Urn> objectOrder)
		{
			if (objectOrder == null)
			{
				return;
			}
			foreach (Urn current in objectOrder)
			{
				this.objectsScripted.AddItem(current);
			}
		}
	}
}
